package com.sinoglobal.wallet.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.TextUtil;
import com.sinoglobal.wallet.util.security.Encryption;


/**
 * @author ty
 * @createdate 2012-9-19 上午10:40:06
 * @Description: Http请求
 */
public class W_ConnectionUtil {

	private static Date serverDate; // 服务器时间
	private static String result = "";

	public static Date getServerDate() {
		return serverDate;
	}

	public static String getCommentUrl(int whichUrl) {
		switch (whichUrl) {
		case SinoConstans.SERVER_FLAG:
			return SinoConstans.SERVER_URL;
		case SinoConstans.SERVER_Encryption_FLAG:
			return SinoConstans.SERVER_Encryption_URL;
		case SinoConstans.SERVER_Coupon_FLAG:
			return SinoConstans.SERVER_Coupon_URL;
		default:
			return SinoConstans.SERVER_URL;
		}
	}
	/**
	 * modify 2015.09.12
	 * @author ty
	 * @createdate 2013-3-21 上午10:22:01
	 * @Description: post请求
	 * @param url
	 *            请求的URL
	 * @param params
	 *            请求的参数封装
	 * @return
	 * @throws Exception
	 * 
	 */
	public static String post(Map<String, Object> params, String name, int urlFlag) throws Exception {
		String json1 = JSON.toJSONString(params);
		// 一下这句话是为了放置 用户输入“/”而造成的 非法字符。
		String json2 = json1.replace("/", "###");
		//String json=json2.replace("\\n", " ");//取消替换换行符操作
		//		String requestUrl = getCommentUrl(urlFlag) + name + json;
		//		LogUtils.i(REQUEST_URL + requestUrl);
		String URLNew = getCommentUrl(urlFlag) + name + URLEncoder.encode(json2, "UTF-8");
		//		LogUtils.i(REQUEST_URL + URLNew);
		LogUtils.i("发送的请求==="+getCommentUrl(urlFlag) + name + json2);
		return httpRequest(new URL(URLNew));
	}
	
	//动态获取秘钥所需的post请求
	public static String postGetKey(String name, int urlFlag) throws Exception {
		// 一下这句话是为了放置 用户输入“/”而造成的 非法字符。
		//String json=json2.replace("\\n", " ");//取消替换换行符操作
		//		String requestUrl = getCommentUrl(urlFlag) + name + json;
		//		LogUtils.i(REQUEST_URL + requestUrl);
		String URLNew = getCommentUrl(urlFlag) + name;
		//		LogUtils.i(REQUEST_URL + URLNew);
		LogUtils.i("发送的请求==="+getCommentUrl(urlFlag) + name );
		return httpRequest(new URL(URLNew));
	}
	public static String postEncrption(Map<String, Object> params, String name, int urlFlag,String id,String key) throws Exception {
		String json1 = JSON.toJSONString(params);
		// 一下这句话是为了放置 用户输入“/”而造成的 非法字符。
		String json2 = json1.replace("/", "###");
		LogUtils.i("加密前==="+json2);
		Encryption.setSkey(key);
		String json3=Encryption.setEncryption(json2);
		LogUtils.i("加密后===="+json3);
		
		String URLNew = getCommentUrl(urlFlag) + name + URLEncoder.encode(URLEncoder.encode(json3, "UTF-8"),"UTF-8")+"&&tradeId="+id;
		//		LogUtils.i(REQUEST_URL + URLNew);
		LogUtils.i("发送的请求==="+URLNew);
		return httpRequest(new URL(URLNew));
	}

	private static String httpRequest(java.net.URL url) {
		try {

			// 第二步：获取HttpURLConnection对象
			HttpURLConnection huc = (HttpURLConnection) url.openConnection();
			huc.setRequestProperty("Accept", "application/json");
			huc.setRequestProperty("Content-Type", "application/json");
			// 第三步：设置请求超时时间
			huc.setConnectTimeout(30000);
			huc.setReadTimeout(30000);
			huc.setDoInput(true);
			huc.setDoOutput(true);
			// 设置 请求方式Get Post
			huc.setRequestMethod("POST");
			LogUtils.d("返回的响应码：" + huc.getResponseCode());
			// 第四步：获取响应吗，进行判断
			result = "";
			if (huc.getResponseCode() == 200) { // HTTP响应消息获取状态码
				BufferedReader in = new BufferedReader(new InputStreamReader(huc.getInputStream()));
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				in.close();
				LogUtils.d( result);
				// System.out.println(result);
				String result1 = result.replace("###", "/");
				return result1;
			}
			huc.getOutputStream().flush();
			huc.getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	//以下是优惠券自己的请求
	/**
	 * 优惠券自己的请求方式
	 * @param params
	 * @param name
	 * @param urlFlag
	 * @return
	 * @throws Exception
	 */
	public static String postNew(Map<String, Object> params, String name, int urlFlag)throws Exception {
		String URLNew = getCommentUrl(urlFlag)+name; 
		HttpPost httpost = new HttpPost(URLNew);
		String json = JSON.toJSONString(params);
		LogUtils.i("请求的url为==" + URLNew);
		LogUtils.i("SUBMIT" + json);
		httpost.setEntity(new StringEntity(json, HTTP.UTF_8));
		return execute(httpost);
	}
	private static String execute(HttpUriRequest req) throws Exception {
		long startTime = System.currentTimeMillis();

		String result = null;
		InputStream instream = null;
		try {
			HttpResponse response = executeLoad(req);
			if (response != null) {
				int statusCode = response.getStatusLine().getStatusCode();
				LogUtils.d("返回码" + statusCode);
				switch (statusCode) {
				case HttpStatus.SC_OK:
					// result = parseResponse(response, instream);
					result = EntityUtils.toString(response.getEntity(), "UTF-8");
					// result = EntityUtils.toString(response.getEntity(),
					// UTF8);GBK
					break;
				case HttpStatus.SC_FORBIDDEN: // 验证未通过
					break;
				case HttpStatus.SC_NOT_FOUND: // 请求错误
					break;
				}
			}
		} finally {
		}

		// 打包时应该注释
		long endTime = System.currentTimeMillis();
		String info = "请求：Time:" + (endTime - startTime) + "-->:"
				+ req.getURI();
		LogUtils.d(info);
		if (TextUtil.stringIsNull(result)) {
			throw new Exception("request not data :" + req.getURI());
		}
		LogUtils.d("返回的result=" + result);
		return result;
	}
	/**
	 * @author ty
	 * @createdate 2012-11-3 下午9:46:54
	 * @Description: 加载数据
	 * @param req
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 * @throws Exception
	 */
	public static HttpResponse executeLoad(HttpUriRequest req) throws ClientProtocolException, IOException  {
		HttpClient httpclient = W_CustomerHttpClient.getInstance();
		req.addHeader("Accept-Charset", "UTF-8,*");
		HttpResponse response = httpclient.execute(req);
		return response;
	}
}
